﻿/* $RCSFile: CrmAttachments.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CrmAttachments/CrmAttachments.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:19  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:47  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.IO;
using System.ComponentModel;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using CrmSdk;

using Telerik.Web.UI;
using Telerik.Web.UI.Upload;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;


namespace AddonNice.PageModules.CrmAttachments
{
 	#region Local TraceSwitch 
	public class CrmAttachmentTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	=	new ADNTraceSwitch("CrmAttachmentTrace","Special Trace Switch for CrmAttachment Trace");
	}
	#endregion Local TraceSwitch 

    public class AStr
    {
        public const string DocumentsFolder     =   "CRMATTACHMENT_DOCUMENTFOLDER";
        public const string UseSiteDefault      =   "CRMATTACHMENT_USE_SITE_DEFAULT";
        public const string ExtendedView        =   "CRMATTACHMENT_EXTENDED_VIEW";
        public const string NewApi              =   "CRMATTACHMENT_NEWAPI";
    }

	/// <summary>
    /// Initializer class for CrmAttachments 
    /// </summary>
    public class CrmAttachmentsSI : PortalCRMModuleControlSI
    {
        public CrmAttachmentsSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmAttachmentsSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmAttachmentsSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmAttachmentsSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);
            string extgrp                       =   pm.ExtendedResourcesGroup;
            
            SettingItemSpecial UseDefaultPath   =   new SettingItemSpecial(AStr.UseSiteDefault,new BooleanDataType());
            UseDefaultPath.Value                =   StStr.strTrue;
            UseDefaultPath.Order                =   2;
            UseDefaultPath.ExtendedGroupName    =   extgrp;
            UseDefaultPath.EnglishName          =   "Use Default Portal Path";
            UseDefaultPath.Description          =   "Take the path set in Site Settings as default Document repository";
            bSettings.AddSetting(UseDefaultPath);

            SettingItemSpecial StDocumentsFolder =   new SettingItemSpecial(AStr.DocumentsFolder,new PortalUrlDataType());
            StDocumentsFolder.Required           =   false;
			StDocumentsFolder.Order              =   10;
            StDocumentsFolder.Value              =   StStr.DocumentsBaseFolderName;
			StDocumentsFolder.ExtendedGroupName  =   extgrp;
            StDocumentsFolder.EnglishName        =	"Virtual Folder for documents";
			StDocumentsFolder.Description        =	"Set the folder where documents will be downloaded/uploaded";
			bSettings.AddSetting(StDocumentsFolder);           

            SettingItemSpecial ExtendedView     =   new SettingItemSpecial(AStr.ExtendedView,new BooleanDataType());
            ExtendedView.Value                  =   StStr.strFalse;
            ExtendedView.Order                  =   20;
            ExtendedView.ExtendedGroupName      =   extgrp;
            ExtendedView.EnglishName            =   "Use extended View";
            ExtendedView.Description            =   "Display all attributes in each entity";
            bSettings.AddSetting(ExtendedView);

            SettingItemSpecial useNewAPI        =   new SettingItemSpecial(AStr.NewApi,new BooleanDataType());
            useNewAPI.Value                     =   StStr.strTrue;
            useNewAPI.Order                     =   30;
            useNewAPI.ExtendedGroupName         =   extgrp;
            useNewAPI.EnglishName               =   "Use Crm4 Rollup7 API";
            useNewAPI.Description               =   "When unchecked use the old CRM3 url loading for content";
            bSettings.AddSetting(useNewAPI);

            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmAttachmentsSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
    }

    public partial class CrmAttachments : PortalCrmProgressModuleControl
    {
        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #region const attribute lists
        string[] ExAnnotationAttributes              =   new string[]{CrmStr.annotationid,
                                                                CrmStr.subject,
                                                                CrmStr.stepid,
                                                                CrmStr.notetext,
                                                                CrmStr.langid,
                                                                CrmStr.mimetype,
                                                                CrmStr.isdocument,
                                                                CrmStr.filename,
                                                                CrmStr.filesize,
                                                                CrmStr.ownerid,
                                                                CrmStr.objecttypecode,
                                                                CrmStr.objectid,
                                                                CrmStr.modifiedby,
                                                                CrmStr.modifiedon,
                                                                CrmStr.createdby,
                                                                CrmStr.createdon,
                                                                CrmStr.importsequencenumber,
                                                                CrmStr.owningbusinessunit
                                                            };

        string[] AnnotationAttributes                =   new string[]{CrmStr.annotationid,
                                                                CrmStr.subject,
                                                                CrmStr.notetext,
                                                                CrmStr.mimetype,
                                                                CrmStr.filename,
                                                                CrmStr.filesize,
                                                                CrmStr.ownerid,
                                                                CrmStr.objecttypecode,
                                                                CrmStr.objectid
                                                                };

        string[] ExsalesliteratureitemAttributes     =   new string[]{CrmStr.salesliteratureitemid,
                                                                CrmStr.title,
                                                                CrmStr.wabstract,
                                                                CrmStr.authorname,
                                                                CrmStr.keywords,
                                                                CrmStr.iscustomerviewable,
                                                                CrmStr.attacheddocumenturl,
                                                                CrmStr.mimetype,
                                                                CrmStr.filetypecode,
                                                                CrmStr.filename,
                                                                CrmStr.filesize,
                                                                CrmStr.salesliteratureid,
                                                                CrmStr.organizationid,
                                                                CrmStr.importsequencenumber,
                                                                CrmStr.modifiedby,
                                                                CrmStr.modifiedon,
                                                                CrmStr.createdby,
                                                                CrmStr.createdon
                                                            };
        string[] salesliteratureitemAttributes       =   new string[]{CrmStr.salesliteratureitemid,
                                                                CrmStr.title,
                                                                CrmStr.wabstract,
                                                                CrmStr.authorname,
                                                                CrmStr.filename,
                                                                CrmStr.filesize,
                                                                CrmStr.salesliteratureid
                                                            };
        string[] ExactivitymimeattachmentAttributes  =   new string[]{CrmStr.activitymimeattachmentid,
                                                                CrmStr.subject,
                                                                CrmStr.attachmentnumber,
                                                                CrmStr.body,
                                                                CrmStr.activityid,
                                                                CrmStr.mimetype,
                                                                CrmStr.filename,
                                                                CrmStr.filesize
                                                            };

        
        string[] activitymimeattachmentAttributes    =   new string[]{CrmStr.activitymimeattachmentid,
                                                                CrmStr.subject,
                                                                CrmStr.attachmentnumber,
                                                                CrmStr.body,
                                                                CrmStr.activityid,
                                                                CrmStr.filename,
                                                                CrmStr.filesize
                                                            };

        #endregion const attribute lists
        
        string SchemaName
        {
            get
            {
                object ob                   =   ViewState["SchemaName"];
                if (ob == null)
                {
                    ViewState["SchemaName"] =   CrmStr.annotation;
                    return CrmStr.annotation;
                }
                return (string)ob;
            }
            set
            {
                ViewState["SchemaName"]     =   value;
            }
        }

        string _ServerUrl           =   string.Empty;
        string ServerUrl
        {
            get
            {
                if (_ServerUrl == string.Empty)
                {
                    _ServerUrl      =           Wrapper.DownloadServerUrl;
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ServerUrl ServerUrl: {0}.",_ServerUrl), ModuleTraceSwitch.Sw.Info);
                }
                return _ServerUrl;
            }
        }

        #region General implementation

        public override bool AdminModule
        {
            get
            {
                return false;
            }
        }

        public override Guid GuidID
        {
            get
            {
                return new Guid("{E1DFDBF6-4474-47ff-B0F2-3943EE90E10D}");
            }
        }
        #endregion General implementation

        #region properties
        
        InternalColumnSet RequestCols   =   null;

        EntityConfig _TConfig           =   null;
        public EntityConfig TConfig
        {
            get
            {
                if (_TConfig == null)
                {
                    _TConfig            =   new EntityConfig(Wrapper,SchemaName);
                    if ( ModuleTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments TConfig Ctor SchemaName: {0}, vflag: [{1}], DisplayMask: [{2}].",
                            SchemaName,_TConfig.entityFlags, _TConfig.DisplayMask),ModuleTraceSwitch.Sw.Info);
                }
                return _TConfig;
            }
        }

        #endregion properties

        public CrmAttachments()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]CrmAttachments Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            ValidationGroup =   "Main";
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "CRMATTACHMENT";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmAttachmentsSI(bSettings,this);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ModuleProgressArea  =   RadProgressArea1;
            InitProgress();
            if (!IsPostBack)
            {
                // Pb localized with strings not maintained  InitProgress();
            }

        }

        byte[] DownLoadFile(string url,ref bool OkDownload)
        {
            byte[] data                             =   null;
            bool Ok                                 =   false;
            try
            {
                data                                =   Wrapper.DownLoadFile(url,ref Ok);
                OkDownload                          =   Ok;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments DownLoadFile url '{0}', ex: {1}.", url, ex), ModuleTraceSwitch.Sw.Info);
            }
            return data;
        }
        
        string DocumentsFolder
        {
            get
            {
                bool UseDefault                     =   Settings[AStr.UseSiteDefault].ToBool();
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments DocumentsFolder UseSiteDefault: {0}.", UseDefault), ModuleTraceSwitch.Sw.Info);
                if ( UseDefault )
                    return portalSettings.DefaultDocumentFolderPath; 
                string path                         =   Server.MapPath(Settings[AStr.DocumentsFolder].FullPath);
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments DocumentsFolder path: {0}.", path), ModuleTraceSwitch.Sw.Info);
                return path;
            }
        }

        string LoadFile(string fileName,ref bool OkLoad)
        {
            string encodedData              =   string.Empty;
            string path                     =   System.IO.Path.Combine(DocumentsFolder,fileName);
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments LoadFile filename '{0}', path: {1}.", fileName, path), ModuleTraceSwitch.Sw.Info);
            FileInfo pointer                =   null;
            FileStream fileStream           =   null;
            OkLoad                          =   false;
            try
            {
                if (File.Exists(path))
                {
                    pointer                 =   new FileInfo(path);
                    fileStream              =   pointer.OpenRead();
                    if (fileStream.Length > 0)
                    {
                        byte[] byteData     =   new byte[(int)fileStream.Length];
                        fileStream.Read(byteData, 0, (int)fileStream.Length);
                        fileStream.Flush();
                        encodedData         =   System.Convert.ToBase64String(byteData);
                        OkLoad              =   true;
                    }
                }
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments LoadFile filename '{0}', ex: {1}.", fileName, ex), ModuleTraceSwitch.Sw.Info);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
            return encodedData;
        }

        /// <summary>
        /// Refresh a file in an attachment
        /// Works only with filename written in entity
        /// Corresponding file must be present in the document folder
        /// file is read, then crm is updated 
        /// </summary>
        bool ResetAttachment(DynEntity newAcc)
        {
            string data64                       =   string.Empty;
            bool isOk                           =   false;
            try
            {
                string filename                 =   newAcc.StringPropertyValue(CrmStr.filename);
                int filsize                     =   newAcc.ContainsKey(CrmStr.filesize) ? newAcc.NumberPropertyValue(CrmStr.filesize):0;
                bool OkLoad                     =   false;
                data64                          =   LoadFile(filename,ref OkLoad);
                if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ResetAttachment salesliteratureitem load Ok: {0}, File: {1}.",
                        OkLoad,filename), (CrmAttachmentTrace.Sw.TraceVerbose) ? CrmAttachmentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                if (OkLoad)
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ResetAttachment annotation data.Length: {0}.", data64.Length), ModuleTraceSwitch.Sw.Info);
                    switch(SchemaName)
                    {
                        case CrmStr.activitymimeattachment:
                            newAcc.AddStringProperty(CrmStr.body, data64);
                        break;
                        case CrmStr.annotation:
                        case CrmStr.salesliteratureitem:
                            newAcc.AddStringProperty(CrmStr.documentbody, data64);
                        break;
                    }
                    newAcc.Update();
                    isOk                    =   true;
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ResetAttachment Ok: {0} for SchemaName: {1}, Id: {2}.",isOk,SchemaName,newAcc.PrimaryKeyGuidValue), ModuleTraceSwitch.Sw.Info);
                }
            }
            catch (SoapException sx)
            {
                if (CrmAttachmentTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments ResetAttachment soap ex : {0}-{1}",sx, sx.Detail.InnerText), ModuleTraceSwitch.Sw.Info);
                throw;
            }
            catch (Exception ex)
            {
                if (CrmAttachmentTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments ResetAttachment  ex : {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ResetAttachment END entity: {0} isOk: {1}.",
                    SchemaName,isOk),(CrmAttachmentTrace.Sw.TraceVerbose)? CrmAttachmentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            return isOk;
        }
        
        void SaveFile(string filename,byte[] buffer)
		{
            bool useSiteDef         =   Settings[AStr.UseSiteDefault].ToBool();
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments SaveFile UseSite Default folder: {0}",useSiteDef),ModuleTraceSwitch.Sw.Info);
            string PathToSave       =   string.Empty;
            string physicalPath		=   string.Empty;
            if (useSiteDef)
            {
                PathToSave          =   portalSettings.DefaultDocumentFolderPath;
                physicalPath        =   System.IO.Path.Combine(PathToSave, filename);
            }
            else
            {
                PathToSave          =   Settings[AStr.DocumentsFolder].FullPath;
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments SaveFile PathToSave: {0}", PathToSave), ModuleTraceSwitch.Sw.Info);
                if (!System.IO.Directory.Exists(Server.MapPath(PathToSave)))
                    System.IO.Directory.CreateDirectory(Server.MapPath(PathToSave));
                string virtualPath  =   AddonNice.Settings.Path.WebPathCombine(PathToSave, filename);
                physicalPath        =   Server.MapPath(virtualPath);
            }
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments SaveFile physicalPath: {0}",physicalPath),ModuleTraceSwitch.Sw.Info);
			// Delete file before upload
			while(File.Exists(physicalPath))
			{
				try
				{
					File.Delete(physicalPath);
				}
				catch(Exception ex)
				{
					if (ModuleTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments SaveFile Deleting: {0}, ex: {1}",physicalPath,ex),ModuleTraceSwitch.Sw.Info);
				}
			}
            FileStream fs           =   null;
            BinaryWriter w          =   null;
            try
            {
                // Save file to uploads directory
                fs                  =   new FileStream(physicalPath, FileMode.Create);
                w                   =   new BinaryWriter(fs);
                w.Write(buffer);
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments SaveFile Ok buffer.Length: {0}.", buffer.Length), ModuleTraceSwitch.Sw.Info);
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments SaveFile Saving: {0}, ex: {1}", physicalPath, ex), ModuleTraceSwitch.Sw.Info);
            }
            finally
            {
                if ( w != null )
                    w.Close();
                if ( fs != null )
                    fs.Close();
            }

		}

        string MakeOpenUrlFmt()
        {
            string url          =   string.Empty;
            int objectTpCode    =   (int)CRMUtil.typeCode(SchemaName);

            switch (SchemaName)
            {
                case CrmStr.annotation:
                    {
                        url     =   string.Format("{0}/Activities/Attachment/download.aspx?AttachmentType=5&AttachmentId={{{{{{0}}}}}}",
                                                                    ServerUrl);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments MakeOpenUrlFmt annotation Url: {0}.", url), ModuleTraceSwitch.Sw.Info);
                    }
                    break;
                case CrmStr.salesliteratureitem:
                    {
                        url     =   string.Format("{0}/Activities/Attachment/download.aspx?AttachmentType={1}&AttachmentId={{{{{{0}}}}}}",
                                                                    ServerUrl, objectTpCode);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments MakeOpenUrlFmt salesliteratureitem Url: {0}.", url), ModuleTraceSwitch.Sw.Info);
                    }
                    break;
                case CrmStr.activitymimeattachment:
                    {
                        url     =   string.Format("{0}/Activities/Attachment/download.aspx?AttachmentType={1}&AttachmentId={{{{{{0}}}}}}",
                                                                    ServerUrl, objectTpCode);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments MakeOpenUrlFmt salesliteratureitem Url: {0}.", url), ModuleTraceSwitch.Sw.Info);
                    }
                    break;
            }
            return url;
        }
        /*
        /// <summary>
        /// Extracts the attached file from CRM and save it in the folder document
        /// </summary>
        bool DownloadAttachment(DynEntity newAcc)
        {
            byte[] data                 =   null;
            bool isOk                   =   false;
            try
            {
                string filename         =   newAcc.StringPropertyValue(CrmStr.filename);
                int filsize             =   0;
                if ( newAcc.ContainsKey(CrmStr.filesize)  )
                    filsize             =   newAcc.NumberPropertyValue(CrmStr.filesize);
                Guid Id                 =   newAcc.PrimaryKeyGuidValue;
                string attachid         =   Id.ToString();
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments DownloadAttachment SchemaName: {0}, attachid: {1}, filename: {2}, fileSize: {3}.",
                        new object[]{SchemaName,attachid,filename,filsize}),ModuleTraceSwitch.Sw.Info);
                string url              =   string.Format(MakeOpenUrlFmt(),attachid);
                bool OkDownload         =   false;
                data                    =   DownLoadFile(url,ref OkDownload);
                if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments DownloadAttachment annotation/attachment download Ok: {0}, File: {1}.",
                        OkDownload,filename), (CrmAttachmentTrace.Sw.TraceVerbose) ? CrmAttachmentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
                if (OkDownload)
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments DownloadAttachment data.Length: {0}.", data.Length), ModuleTraceSwitch.Sw.Info);
                    SaveFile(filename,data);
                }
            }
            catch (SoapException sx)
            {
                if (CrmAttachmentTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments DownloadAttachment soap ex : {0}-{1}",sx, sx.Detail.InnerText), ModuleTraceSwitch.Sw.Info);
                throw;
            }
            catch (Exception ex)
            {
                if (CrmAttachmentTrace.Sw.TraceError || ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments DownloadAttachment  ex : {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments DownloadAttachment END entity: {0} isOk: {1}.",
                    SchemaName,isOk),(CrmAttachmentTrace.Sw.TraceVerbose)? CrmAttachmentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            return isOk;
        }
        */

        /// <summary>
        /// Build a DataTable to display in in RadGrid
        /// </summary>
        public DataTable ReadForGrid()
        {
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ReadForGrid BEG SchemaName: {0}.",SchemaName),(CrmAttachmentTrace.Sw.TraceVerbose)? CrmAttachmentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            DataTable Tb                                    =   null;
            _TConfig                                        =   null;
            try
            {
                InternalQueryExpression qe                  =   new InternalQueryExpression();
                qe.EntityName                               =   SchemaName;
                RequestCols                                 =   new InternalColumnSet();
                InternalFilterExpression fi                 =   new InternalFilterExpression();
                InternalConditionExpression ex              =   new InternalConditionExpression();
                bool extendedView                           =   Settings[AStr.ExtendedView].ToBool();
                switch(SchemaName)
                {
                    case CrmStr.annotation:
                        if ( extendedView )
                                RequestCols.Attributes      =   ExAnnotationAttributes;
                        else    RequestCols.Attributes      =   AnnotationAttributes;

                        ex.AttributeName                    =   CrmStr.isdocument;
                        ex.Operator                         =    InternalConditionOperator.Equal;
                        ex.Values                           =   new object[]{true};
                        fi.Conditions                       =   new InternalConditionExpression[]{ex};
                    break;
                    case CrmStr.salesliteratureitem:
                        if ( extendedView )
                                RequestCols.Attributes      =   ExsalesliteratureitemAttributes;
                        else    RequestCols.Attributes      =   salesliteratureitemAttributes;
                        ex.AttributeName                    =   CrmStr.filename;
                        ex.Operator                         =   InternalConditionOperator.NotNull;
                        ex.Values                           =   new object[0];
                        fi.Conditions                       =   new InternalConditionExpression[]{ex};
                    break;
                    case CrmStr.activitymimeattachment:
                        if ( extendedView )
                                RequestCols.Attributes      =   ExactivitymimeattachmentAttributes;
                        else    RequestCols.Attributes      =   activitymimeattachmentAttributes;
                        ex.AttributeName                    =   CrmStr.filename;
                        ex.Operator                         =   InternalConditionOperator.NotNull;
                        ex.Values                           =   new object[0];
                        fi.Conditions                       =   new InternalConditionExpression[]{ex};
                    break;
                 }
                qe.ColumnSet                                        =   RequestCols;
                qe.Criteria                                         =   fi;
                GenericDynQueryMultiple<DynEntity> allEntQuery      =   new GenericDynQueryMultiple<DynEntity>(Wrapper,ResetWrapper,SchemaName);
                Tb                                                  =   allEntQuery.retrieveDatatable(qe);
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments ReadForGrid ex : {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ReadForGrid END entity: {0}, Count: {1}",SchemaName,Tb.Rows.Count),(CrmAttachmentTrace.Sw.TraceVerbose)? CrmAttachmentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            return Tb;
        }

        public List<ADNDynCommonDoc> ReadAll(bool reset)
        {
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ReadAll BEG SchemaName: {0}, Reset: {1}.",SchemaName,reset),(CrmAttachmentTrace.Sw.TraceVerbose)? CrmAttachmentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            int count                                           =   0;
            List<ADNDynCommonDoc> dynEntList                          =   new List<ADNDynCommonDoc>();
            try
            {
                GenericDynQueryMultiple<DynEntity> allEntQuery  =   new GenericDynQueryMultiple<DynEntity>(Wrapper,null,SchemaName);
                InternalBusinessEntityCollection allEnt         =   allEntQuery.Retrieve();
                PropertyDescriptorCollection _columnDescriptors =   null;
                _TConfig                                        =   null;
                Wrapper.Util.ExecForEachDynamicEntity(allEnt,
                    delegate(InternalDynamicEntity de)
                    {
                        ADNDynCommonDoc ob                      =   (ADNDynCommonDoc)DynEntity.CreateFromDynamicEntity(Wrapper, de, _columnDescriptors);
                        ob.EntityMData                          =   TConfig.entityMetaData;
                        _columnDescriptors                      =   ob.PropertyDescriptorCollection;
                        // We skip annotations which have no documents attached
                        if (SchemaName == CrmStr.annotation)
                        {
                            bool isDocument                     =   false;
                            if (ob.dicProperty.ContainsKey(CrmStr.isdocument))
                                isDocument                      =   ob.BooleanPropertyValue(CrmStr.isdocument);
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ReadAll annotation isDocument: {0}.", isDocument), ModuleTraceSwitch.Sw.Info);
                            if (!isDocument)
                                return true; //continue
                        }
                        dynEntList.Add(ob);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ReadAll after Ctor schemaName: [{0}], type: {1}", ob.SchemaName, ob), ModuleTraceSwitch.Sw.Info);
                        return true; //continue
                    });
                count                                           =   dynEntList.Count;
                ProgressTotalSteps                              =   count;
                StartProgress();
                if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ReadAll SchemaName: {0} found Count: {1}.", SchemaName, count), (CrmAttachmentTrace.Sw.TraceVerbose) ? CrmAttachmentTrace.Sw.Info : ModuleTraceSwitch.Sw.Info);
                for (int i = 0; i < count; i++)
                {
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ReadAll entity: {0}, i: {1}/{2}", SchemaName, i + 1, count), ModuleTraceSwitch.Sw.Info);
                    ADNDynCommonDoc s                           =   dynEntList[i];
                    string PrimaryFieldStringValue              =   s.PrimaryFieldStringValue;
                    SetUpdateProgress(string.Format("{0} '{1}'", SchemaName, PrimaryFieldStringValue), ProgressPrimCount, ProgressSecCount++);
                    if (reset)
                        ResetAttachment(s);
                    else
                    {
                        if ( Settings[AStr.NewApi].ToBool() )
                        {
                             byte[] data =   s.DownloadAttachment2(false,string.Empty);
                            if (( data != null ) && ( data.Length > 0 ) )
                                SaveFile(s.filename,data);
                        }
                        else
                        {
                        bool isOk   =   false;
                        byte[] data =   s.DownloadAttachment(false,string.Empty,ref isOk);
                        if ( isOk )
                            SaveFile(s.filename,data);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments ReadAll ex : {0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
            finally
            {
                EndProgress();
            }
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments ReadAll END entity: {0}, Count: {1}",SchemaName,count),(CrmAttachmentTrace.Sw.TraceVerbose)? CrmAttachmentTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            return dynEntList;
        }
        
        /// <summary>
        /// For each attachment try to find a corresponding file in the document folder then upgrade the attachment
        /// </summary>
        void resetBtn_Click(object sender, ImageClickEventArgs e)
        {
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmAttachments resetBtn_Click BEG.",ModuleTraceSwitch.Sw.Info);
            try
            {
                ReadAll(true);
            }
            catch (SoapException sex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments resetBtn_Click soap ex :{0}", sex), ModuleTraceSwitch.Sw.Info);
                //e.Cancel                =   true;
                return;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments resetBtn_Click ex :{0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmAttachments resetBtn_Click END.",ModuleTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// Extract all attachments in the dedicated folder
        /// </summary>
        void CrmAttachments_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmAttachments CrmAttachments_ADNUpdateModule BEG.",ModuleTraceSwitch.Sw.Info);
            try
            {
                ReadAll(false);
            }
            catch (SoapException sex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments CrmAttachments_ADNUpdateModule soap ex :{0}", sex), ModuleTraceSwitch.Sw.Info);
                e.Cancel                =   true;
                return;
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmAttachments CrmAttachments_ADNUpdateModule ex :{0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmAttachments CrmAttachments_ADNUpdateModule END.",ModuleTraceSwitch.Sw.Info);
        }
        

        #region Attachments Grid Management
        
        void RadGrid1_PreRender(object sender, System.EventArgs e)
        {
            foreach(GridColumn column in RadGrid1.Columns)
            {
                    if (column.UniqueName == "ViewLink")
                    {
                        GridHyperLinkColumn col =   (GridHyperLinkColumn)column;
                        col.DataNavigateUrlFormatString = MakeOpenUrlFmt();
                        col.Target  =   "_new";
                        switch (SchemaName)
                        {
                            case CrmStr.annotation:
                                col.DataNavigateUrlFields   = new string[]{CrmStr.annotationid};
                                break;
                            case CrmStr.salesliteratureitem:
                                col.DataNavigateUrlFields   = new string[]{CrmStr.salesliteratureitemid};
                                break;
                            case CrmStr.activitymimeattachment:
                                col.DataNavigateUrlFields   = new string[]{CrmStr.activitymimeattachmentid};
                                break;
                        }
                        if (CrmAttachmentTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_PreRender url {0}.",col.DataNavigateUrlFormatString),ModuleTraceSwitch.Sw.Info);
                        break;
                   }
                }
            RadGrid1.Rebind();
        }

        void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            if ( !(e.Column is GridBoundColumn))
                return;
            string colName                  =   ((GridBoundColumn)e.Column).DataField;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ColumnCreated colName: {0}, HeaderText: {1}",colName,e.Column.HeaderText ),ModuleTraceSwitch.Sw.Info);
            if (colName.IndexOf(CrmStr.InternalRowTypecode) > 0 ||
                    colName.IndexOf(CrmStr.InternalRowVal) > 0)
            {
                //e.Column.Display            =   false;
                e.Column.Visible            =   false;
                return;
            }
            string primkId                  =   SchemaName+"id";
            // don't display items Guids
            if ( SchemaName.Equals(colName) || primkId.Equals(colName) )
            {
                //e.Column.Display            =   false;
                e.Column.Visible            =   false;
                return;
            }
            InternalAttributeMetadata att   =   TConfig[colName];
            if ( att == null )
                return;
            string DisplayName              =   Wrapper.Util.ExtractAttributeFieldAsString(att,InternalAttributeFields.DisplayName);
            if ( string.IsNullOrEmpty(DisplayName) )
                return;
            e.Column.HeaderText             =   DisplayName;
        }

       void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound BEG ItemType: {0}, DataItem: {1}", e.Item.ItemType,e.Item.DataItem), ModuleTraceSwitch.Sw.Info);
            if (!(e.Item.ItemType == GridItemType.Item ) &&
                !(e.Item.ItemType == GridItemType.AlternatingItem ))
                return;
            if ( !(e.Item is GridDataItem ) )
                return;
            GridDataItem item                       =   (GridDataItem)e.Item;
            bool ok                                 =   true;
           // Jump over the Primary key in first position 
           for (int i = 1; i < RequestCols.Attributes.Length && ok ; i++)
            {
                string strschemaName                =   RequestCols.Attributes[i];
                InternalAttributeMetadata att       =   TConfig[strschemaName];
                AttributeInternalType attributType  =   (AttributeInternalType)Wrapper.Util.ExtractAttributeFieldAsInt(att,InternalAttributeFields.AttributeType);
                string strVal                       =   item[strschemaName].Text.Trim();
                if ( string.IsNullOrEmpty(strVal) || strVal.Equals(StStr.HTML_SPACE)  ) // Null value 
                    continue;
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound col: {0}, value: {1}",strschemaName,strVal), ModuleTraceSwitch.Sw.Info);
                string strVal2                      =   string.Empty;
                if ( strschemaName == CrmStr.objecttypecode && attributType == AttributeInternalType.Picklist)
                {
                    attributType = AttributeInternalType.EntityNameReference;
                    if ( CRMQueryTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound changing type for Key: {0}.",strschemaName),CRMQueryTraceSwitch.Sw.Info);
                }
                switch (attributType)
                {
                    case AttributeInternalType.Status:
                    {
                        strVal2                 =   item[strschemaName+CrmStr.InternalRowTypecode].Text.Trim();
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound StatusVal: {0}",strVal2), ModuleTraceSwitch.Sw.Info);
                        break;
                    }
                    case AttributeInternalType.Picklist:
                    {
                        strVal2                 =   item[strschemaName+CrmStr.InternalRowTypecode].Text.Trim();
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound PickListVal: {0}",strVal2), ModuleTraceSwitch.Sw.Info);
                        break;
                    }
                    case AttributeInternalType.Owner:
                    {
                        Guid ownerId            =   new Guid(strVal);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound ownerId: {0}",ownerId), ModuleTraceSwitch.Sw.Info);
                        string suDisplay        =   item[strschemaName+CrmStr.InternalRowVal].Text.Trim();
                        ADNDynSystemUser sysuser =   DynEntity.FindOwner(Wrapper,ownerId,suDisplay);
                        strVal2                 =   sysuser.fullname;
                        if (strVal2.Equals(string.Empty))
                        {
                            strVal2                 =   suDisplay;
                        }
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound Owner: {0}",strVal2), ModuleTraceSwitch.Sw.Info);
                        break;
                    }
                    case AttributeInternalType.UniqueIdentifier:
                    {
                        if ( strschemaName != CrmStr.organizationid )
                            break;
                        Guid CrmId            =   new Guid(strVal);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound UniqueIdentifier: {0}",CrmId), ModuleTraceSwitch.Sw.Info);
                        DynEntity dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.organization,CrmId);
                        if ( dynEnt == null )
                            break;
                         strVal2             =   dynEnt.PrimaryFieldStringValue;
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound UniqueIdentifier: {0}",strVal2), ModuleTraceSwitch.Sw.Info);
                        break;
                    }
                    case AttributeInternalType.PrimaryKey:
                        break;
                    case AttributeInternalType.DateTime:
                        break;
                    case AttributeInternalType.Lookup:
                    {
                        Guid CrmId              =   new Guid(strVal);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound lookup CrmId: {0}",CrmId), ModuleTraceSwitch.Sw.Info);
                        string typenm           =   item[strschemaName+CrmStr.InternalRowTypecode].Text.Trim();
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound lookup typename: [{0}]",typenm), ModuleTraceSwitch.Sw.Info);
                        string lkDisplay        =   item[strschemaName+CrmStr.InternalRowVal].Text.Trim();
                        DynEntity dEnt          = DynEntity.RetrieveLookup(Wrapper,SchemaName,TConfig,strschemaName,CrmId,lkDisplay);
                        if ( dEnt != null )
                            strVal2             =   dEnt.PrimaryFieldStringValue;
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound lookup: {0}",strVal2), ModuleTraceSwitch.Sw.Info);
                        if (strVal2.Equals(string.Empty))
                        {
                            strVal2                 =   lkDisplay;
                        }
                        break;
                    }
                    case AttributeInternalType.Customer:
                    {
                        Guid CrmId              =   new Guid(strVal);
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound Customer CrmId: {0}",CrmId), ModuleTraceSwitch.Sw.Info);
                        string typenm           =   item[strschemaName+CrmStr.InternalRowTypecode].Text.Trim();
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound Customer typename: [{0}]",typenm), ModuleTraceSwitch.Sw.Info);
                        string cuDisplay        =   item[strschemaName+CrmStr.InternalRowVal].Text.Trim();
                        if ( !typenm.Equals(string.Empty) )
                        {
                            DynEntity dEnt          =   DynEntity.RetrieveCustomer(Wrapper,SchemaName,strschemaName,CrmId,typenm,cuDisplay);
                            if ( dEnt != null )
                                strVal2                 =   dEnt.PrimaryFieldStringValue;
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound Customer: {0}",strVal2), ModuleTraceSwitch.Sw.Info);
                        }
                        if (strVal2.Equals(string.Empty))
                        {
                            strVal2                 =   cuDisplay;
                        }
                        break;
                    }
                }
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_ItemDataBound col: {0}, oldvalue: {1}, new value: {2}",strschemaName,strVal,strVal2), ModuleTraceSwitch.Sw.Info);
                if ( strVal2 != string.Empty )
                    item[strschemaName].Text        =   strVal2;
            }

            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CrmAttachments RadGrid1_ItemDataBound END.", ModuleTraceSwitch.Sw.Info);
        }
        
        private void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmAttachments RadGrid1_NeedDataSource BEG RebindReason: {0}.",e.RebindReason),ModuleTraceSwitch.Sw.Info);
            RadGrid1.DataSource     =   ReadForGrid();
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]CrmAttachments RadGrid1_NeedDataSource END.",ModuleTraceSwitch.Sw.Info);
        }

        #endregion Attachment Grid Management

        #region Combo management
        void RadComboAttach_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            switch (e.Value)
            {
                case "0":
                    SchemaName  =   CrmStr.annotation;
                    break;
                case "1":
                    SchemaName  =   CrmStr.salesliteratureitem;
                    break;
                case "2":
                    SchemaName  =   CrmStr.activitymimeattachment;
                    break;
            }
            RadGrid1.DataSource =   null;
            RadGrid1.Rebind();
        }
        #endregion Combo management
        
        #region Std Control override
 
        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID    =   "Extract_" + strcult;
            resetBtn.SkinID    =   "Reset_" + strcult;
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }
        
        private void InitializeComponent()
        {
            Load                                +=      new EventHandler(Page_Load);
            ADNUpdateModule                     +=      new PortalModuleEventHandler(CrmAttachments_ADNUpdateModule);
            resetBtn.Click                      +=      new ImageClickEventHandler(resetBtn_Click);
            RadComboAttach.SelectedIndexChanged +=      new RadComboBoxSelectedIndexChangedEventHandler(RadComboAttach_SelectedIndexChanged);
            RadGrid1.NeedDataSource             +=      new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.ColumnCreated              +=      new GridColumnCreatedEventHandler(RadGrid1_ColumnCreated);
            RadGrid1.ItemDataBound              +=      new GridItemEventHandler(RadGrid1_ItemDataBound);
            RadGrid1.PreRender                  +=      new EventHandler(RadGrid1_PreRender);
      }

      #endregion Std Control override
    }
}